from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from models import db, Diagram, RequirementPool
from datetime import datetime

diagram_bp = Blueprint('diagram', __name__, url_prefix='/diagram')

@diagram_bp.route('/create/<string:req_id>', methods=['GET'])
def create_diagram(req_id):
    diagram_type = request.args.get('type', 'erd')
    return render_template('diagram/editor.html', 
                          req_id=req_id, 
                          diagram_type=diagram_type,
                          title=f"新建{get_diagram_name(diagram_type)}图")

@diagram_bp.route('/edit/<int:diagram_id>', methods=['GET'])
def edit_diagram(diagram_id):
    diagram = Diagram.query.get_or_404(diagram_id)
    return render_template('diagram/editor.html', 
                          diagram=diagram,
                          title=f"编辑{get_diagram_name(diagram.diagram_type)}图")

@diagram_bp.route('/save', methods=['POST'])
def save_diagram():
    try:
        data = request.get_json()
        
        # 输入验证
        if not data or 'code' not in data or 'req_id' not in data:
            return jsonify({"status": "error", "message": "缺少必要参数"}), 400
        
        diagram_id = data.get('id')
        title = data.get('title', f"{get_diagram_name(data['type'])}图")
        req_id = data['req_id']
        diagram_type = data.get('type', 'erd')
        code = data['code']
        
        if diagram_id:
            # 更新现有图表
            diagram = Diagram.query.get(diagram_id)
            if diagram:
                diagram.mermaid_code = code
                diagram.title = title
                db.session.commit()
                return jsonify({"status": "success", "id": diagram.id})
        else:
            # 创建新图表
            new_diagram = Diagram(
                req_id=req_id,
                diagram_type=diagram_type,
                title=title,
                mermaid_code=code
            )
            db.session.add(new_diagram)
            db.session.commit()
            return jsonify({"status": "success", "id": new_diagram.id})
        
        return jsonify({"status": "error", "message": "图表未找到"}), 404
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "status": "error", 
            "message": f"保存失败: {str(e)}"
        }), 500
@diagram_bp.route('/preview', methods=['POST'])
def preview_diagram():
    code = request.json.get('code', '')
    return jsonify({"svg": render_mermaid_svg(code)})

@diagram_bp.route('/delete/<int:diagram_id>', methods=['POST'])
def delete_diagram(diagram_id):
    diagram = Diagram.query.get_or_404(diagram_id)
    db.session.delete(diagram)
    db.session.commit()
    return jsonify({"status": "success"})

def get_diagram_name(d_type):
    names = {
        'erd': '实体关系',
        'sequence': '时序交互',
        'flowchart': '业务流程'
    }
    return names.get(d_type, '图表')

def render_mermaid_svg(code):
    # 实际实现需要使用Mermaid CLI或API
    # 这里是简化版，实际开发中需要调用渲染服务
    return f'<div class="mermaid">{code}</div>'